package com.mijie.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.mijie.core.ApplicationProperties;

public class HttpUtil {

	private static Logger logger = Logger.getLogger(HttpUtil.class);
	
	public static String getIp(HttpServletRequest request) {   
	     String ip = request.getHeader("x-forwarded-for");   
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)    
	                   || "null".equalsIgnoreCase(ip))    {   
	         ip = request.getHeader("Proxy-Client-IP");   
	     }   
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)    
	                   || "null".equalsIgnoreCase(ip)) {   
	         ip = request.getHeader("WL-Proxy-Client-IP");   
	     }   
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)    
	                   || "null".equalsIgnoreCase(ip)) {   
	         ip = request.getRemoteAddr();   
	     }   
	     return ip;   
	 }
	
	public static String loginThroughHomiAccount(String account,String password){
		String homiApi = ApplicationProperties.get("homi.api");
		if(homiApi==null || homiApi.trim().isEmpty()) homiApi = "http://api.51homi.com:8282";
		String url = homiApi+"/user/info.json?account="+account+"&password="+password;
		String result = null;
		try {
			result = request(url, "GET", "UTF-8", null);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return result;
	}
	
	public static String request(String urlStr,String method,String encoding,String content) throws Exception{
		URL url = null;
		HttpURLConnection connection = null;
		StringBuilder sb = new StringBuilder();
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);
			connection.setInstanceFollowRedirects(true); 
			connection.setUseCaches(false);
			connection.setReadTimeout(1000*30);
			connection.setConnectTimeout(1000*30);
			connection.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE 6.0;Windows 2002)"); 
			connection.connect();
			if(content!=null && method.equalsIgnoreCase("POST")){
				OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(),encoding);
				BufferedWriter out = new BufferedWriter(osw);
				out.write(content);
				out.flush();
				out.close();
			}
			if(connection.getResponseCode()==200){
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection
				.getInputStream(), encoding));
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				reader.close();
			}
		} catch (Exception e) {
			logger.error("URL:"+url+",Methos:"+method+",Code:"+connection.getResponseCode());
			logger.error(e.getMessage(), e);
			throw e;
		} finally {
			if (connection != null) 
				connection.disconnect();
		}
		return sb.toString();
	}
	
	public static Integer getInteger(HttpServletRequest request,String name){
		String tmp = request.getParameter(name);
		Integer result = null;
		if(tmp!=null && Helper.isInt(tmp)){
			result = Integer.parseInt(tmp);
		}
		return result;
	}
	
	public static int getInt(HttpServletRequest request,String name){
		String tmp = request.getParameter(name);
		int result = 0;
		if(tmp!=null && Helper.isInt(tmp)){
			result = Integer.parseInt(tmp);
		}
		return result;
	}
	
	public static int[] getInts(HttpServletRequest request,String name){
		String[] array = request.getParameterValues(name);
		int[] result = null;
		if(array!=null){
			result = new int[array.length];
			String num  = null;
			for(int index=0;index<array.length;index++){
				num = array[index];
				if(num==null || num.trim().isEmpty() || !Helper.isInt(num.trim()))
					result[index] = 0;
				else
					result[index] = Integer.parseInt(num);
			}
		}
		return result;
	}
	
	
}
